package me.zhengjie.modules.member.rest;

import com.qiaofang.applet.service.member.domain.Employee;
import com.qiaofang.applet.service.member.domain.Member;
import com.qiaofang.applet.service.member.service.EmployeeService;
import com.qiaofang.applet.service.member.service.MemberService;
import com.qiaofang.applet.service.member.service.dto.MemberDto;
import com.qiaofang.applet.service.member.service.dto.MemberQueryDto;
import com.qiaofang.applet.service.other.domain.Corporation;
import com.qiaofang.applet.service.other.service.CityCompanyService;
import com.qiaofang.applet.service.other.service.CorporationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import me.zhengjie.annotation.AnonymousAccess;
import me.zhengjie.modules.member.vo.MemberExcelVo;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.utils.DateUtil;
import me.zhengjie.utils.ExcelUtil;
import me.zhengjie.utils.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.IOException;
import java.text.ParseException;
import java.util.*;


/**
 * Created by IDEA.
 *
 * @author QF2019
 * @company qiaofang
 * @date 2020/9/12 11:35
 */
@RestController
@RequiredArgsConstructor
@Api(tags = "其它：会员管理")
@RequestMapping("/api/member")
public class MemberController {

    private final static Logger LOGGER = LoggerFactory.getLogger(MemberController.class);

    @Autowired
    private MemberService memberService;

    @Autowired
    private CityCompanyService cityCompanyService;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private CorporationService corporationService;

    @Autowired
    private UserService userService;

    @GetMapping
    @ApiOperation(value = "查询会员管理列表", notes = "查询会员管理列表")
    public ResponseEntity<Page<MemberDto>> list(MemberQueryDto memberQueryDto, Pageable pageable) {
        memberQueryDto.setCorporationCode(SecurityUtils.getCorporationCode());
//        List<String> cityCodeList = userService.getCityCodeList(SecurityUtils.getCurrentUsername());
//        memberQueryDto.setCityCodeList(cityCodeList);
        Page<MemberDto> page = memberService.findByParams(memberQueryDto, pageable);
        return ResponseEntity.ok(page);
    }

    /**
     * 会员Excel导入
     *
     * @param request
     * @return
     */
    @PostMapping("/importExcel")
    @ApiOperation(value = "会员批量导入", notes = "会员批量导入")
    @AnonymousAccess
    public ResponseEntity<Object> importExcel(MultipartHttpServletRequest request) {
        long l = System.currentTimeMillis();
        Map<String, MultipartFile> fileMap = request.getFileMap();
        MultipartFile file = fileMap.get("file");
        ExcelUtil<MemberExcelVo> util = new ExcelUtil<>(MemberExcelVo.class);
        String filename = file.getOriginalFilename();
        List<MemberExcelVo> list = null;
        String[] split = filename.split("\\.");
        if (split.length != 2) {
            return ResponseEntity.ok("请上传正确格式的Excel文件！");
        }
        String corporationCode = split[0];
        Corporation corporation = new Corporation();
        corporation.setCorporationCode(corporationCode);
        corporation.setDeleted(false);
        Optional<Corporation> optional = corporationService.findOne(Example.of(corporation));
        if (!optional.isPresent()) {
            return ResponseEntity.ok("集团" + split[0] + "不存在！");
        }
        try {
            if (filename.endsWith("xls")) {
                list = util.importExcelHSSF(file.getInputStream());
            } else if (filename.endsWith("xlsx")) {
                list = util.importExcelXSSF(file.getInputStream());
            } else {
                return ResponseEntity.ok("请上传正确格式的Excel文件！");
            }
        } catch (IOException e) {
            LOGGER.error("解析会员列表文件失败", e);
            return ResponseEntity.ok("解析会员列表文件失败！");
        }
        if (CollectionUtils.isEmpty(list)) {
            return ResponseEntity.ok("没有获取到有效会员数据！");
        }
        int i = 0;
        Set<String> distinctVerify = new HashSet<>();
        List<Member> saveList = new ArrayList<>(list.size());
        for (MemberExcelVo memberExcelVo : list) {
            String mobilePhone = memberExcelVo.getMobilePhone();
            if (distinctVerify.contains(mobilePhone)){
                continue;
            }
            distinctVerify.add(mobilePhone);
            String name = memberExcelVo.getName();
            Date registerTime = memberExcelVo.getRegisterTime();
            Date lastLoginTime = memberExcelVo.getLastLoginTime();
            String openid = memberExcelVo.getOpenid();
            String memberCityName = memberExcelVo.getMemberCityName();
            Member member = memberService.findByMobilePhoneAndCorporationCode(mobilePhone, corporationCode);
            if (member == null) {
                member = new Member();
                member.setMobilePhone(mobilePhone);
                member.setName(name);
                member.setRegisterTime(registerTime);
                member.setLastLoginTime(lastLoginTime);
                member.setOpenid(openid);
                member.setMemberCityName(memberCityName);
                member.setSource(1);
                member.setSourceName("移动端");
                member.setMemberType(1);
                member.setMemberTypeName("普通用户");
                member.setCorporationCode(corporationCode);
                List<Employee> employeeList = employeeService.findByCorporationCodeAndMobilePhone(corporationCode, mobilePhone);
                if (!CollectionUtils.isEmpty(employeeList)) {
                    Employee employee = employeeList.get(0);
                    member.setMemberType(2);
                    member.setMemberTypeName("经纪人");
                    member.setEmployeeUniqueUuid(employee.getEmployeeUniqueUuid());
                    member.setCompanyUuid(employee.getCompanyUuid());
                }
            } else {
                member.setName(name);
                member.setRegisterTime(registerTime);
                member.setLastLoginTime(lastLoginTime);
                member.setMemberCityName(memberCityName);
                member.setOpenid(openid);
            }
            saveList.add(member);
            i++;
        }
        if (i > 0) {
            memberService.saveAll(saveList);
        }
        System.err.println(System.currentTimeMillis() - l);
        return ResponseEntity.ok(i);
    }
}